//
//  MKUITestCircleGestureView.m
//  MKUITestApp
//
//  Created by 苏尚进 on 2025/8/7.
//  Copyright © 2025 moon. All rights reserved.
//

#import "MKUITestCircleGestureView.h"

@interface MKUITestCircleCellBase()
@property(nonatomic,assign) NSInteger cellIndex;
@property(nonatomic,assign) BOOL selected;
@property(nonatomic,assign) BOOL isTrackHidden;//是否隐藏轨迹
@end

@implementation MKUITestCircleCellBase
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        self.clipsToBounds = YES;
        self.layer.borderWidth = 1;
    }
    return self;
}
+ (nullable UIColor *)tintColorWithSelected:(BOOL)selected{
    UIColor *c = selected?UIColor.systemBlueColor:UIColor.systemGrayColor;
    return c;
}
- (void)setSelected:(BOOL)selected{
    if(_selected==selected)return;
    _selected = selected;
    [self reloadCell];
    [self setNeedsLayout];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated{
    self.selected = selected;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    CGRect bounds = self.bounds;
    self.layer.cornerRadius = MIN(bounds.size.width*0.5,bounds.size.height*0.5);
}
- (void)reloadCell{
    BOOL selected = self.selected&&!self.isTrackHidden;
    self.layer.borderColor = [self.class tintColorWithSelected:selected].CGColor;
}
@end

//单个圆圈视图
@interface MKUITestCircleCell()
@property(nonatomic,strong) UIView *centerCircleView;//中心圆圈视图
@end
@implementation MKUITestCircleCell
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        self.centerCircleView = [[UIView alloc] init];
        self.centerCircleView.clipsToBounds = YES;
        [self addSubview:self.centerCircleView];
    }
    return self;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    CGRect bounds = self.bounds;
    CGRect f1 = bounds;
    CGFloat scale = 0.35;
    f1.size.width = bounds.size.width*scale;
    f1.size.height = bounds.size.height*scale;
    f1.origin.x = bounds.origin.x+(bounds.size.width-f1.size.width)*0.5;
    f1.origin.y = bounds.origin.y+(bounds.size.height-f1.size.height)*0.5;
    self.centerCircleView.frame = f1;
    self.centerCircleView.layer.cornerRadius = MIN(f1.size.width*0.5,f1.size.height*0.5);
}
- (void)reloadCell{
    [super reloadCell];
    BOOL selected = self.selected&&!self.isTrackHidden;
    self.centerCircleView.backgroundColor = [self.class tintColorWithSelected:selected];
    self.centerCircleView.hidden = !selected;
}
@end

@interface MKUITestCircleGestureView(){
    NSMutableArray<NSNumber *> *_selectedCircleIndexes;
}
@property(nonatomic,assign) NSInteger cols;//列数，默认为3
@property(nonatomic,assign) NSInteger rows;//行数，默认为3
@property(nonatomic,strong) UIView *contentView;
@property(nonatomic,strong) NSArray<MKUITestCircleCellBase *> *circleCells;
@property(nonatomic,assign) BOOL needReloadCells;
@property(nonatomic,assign) BOOL isTouching;//是否正在手势滑动
@property(nonatomic,assign) CGPoint touchingPoint;//当前选中的点，坐标系为self.contentView
@property(nonatomic,strong,nullable) NSMutableArray<MKUITestCircleCellBase *> *selectedCircleCells;//选择的圈圈数组
@end

@implementation MKUITestCircleGestureView
- (id)initWithCols:(NSInteger)cols rows:(NSInteger)rows{
    if(self=[super initWithFrame:CGRectZero]){
        self.backgroundColor = UIColor.clearColor;
        self.cols = cols;
        self.rows = rows;
        self.clearSelectionWhenTouchBegin = YES;
        _selectedCircleIndexes = [[NSMutableArray alloc] initWithCapacity:self.cols*self.rows];
        self.selectedCircleCells = [[NSMutableArray alloc] initWithCapacity:self.cols*self.rows];
        
        self.contentInsets = UIEdgeInsetsZero;
        self.circleInteritemSpacing = 10;
        self.minCircleInteritemSpacing = 2;
        self.circleRadius = 22;
        self.minCircleRadius = 11;
        self.lineWidth = 1;
        self.lineColor = UIColor.systemBlueColor;
        self.contentView = [[UIView alloc] init];
        self.contentView.userInteractionEnabled = NO;//只让self可以响应事件，circleCell不响应，防止在手势滑动中，修改了circleCellClass
        [self addSubview:self.contentView];
        _circleCellClass = MKUITestCircleCell.class;
        [self initCells];
    }
    return self;
}
- (id)initWithFrame:(CGRect)frame{
    return [self initWithCols:3 rows:3];
}
- (CGSize)sizeThatFits:(CGSize)size{
    UIEdgeInsets insets = self.contentInsets;
    CGSize limitSize = CGSizeMake(size.width-insets.left-insets.right, size.height-insets.top-insets.bottom);
    CGSize s = limitSize;
    //
    CGFloat minWidth = self.minCircleRadius*2*self.cols+self.minCircleInteritemSpacing*(self.cols-1);
    CGFloat maxWidth = self.circleRadius*2*self.cols+self.circleInteritemSpacing*(self.cols-1);
    s.width = MAX(s.width,minWidth);
    s.width = MIN(s.width,maxWidth);
    s.width += insets.left+insets.right;
    //
    CGFloat minHeight = self.minCircleRadius*2*self.rows+self.minCircleInteritemSpacing*(self.rows-1);
    CGFloat maxHeight = self.circleRadius*2*self.rows+self.circleInteritemSpacing*(self.rows-1);
    s.height = MAX(s.height,minHeight);
    s.height = MIN(s.height,maxHeight);
    s.height += insets.top+insets.bottom;
    return s;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    self.contentView.frame = UIEdgeInsetsInsetRect(self.bounds, self.contentInsets);
    
    CGRect bounds = self.contentView.bounds;
    //计算cellWidth
    CGFloat minCellWidth = (bounds.size.width-(self.cols-1)*self.circleInteritemSpacing)/self.cols;
    CGFloat maxCellWidth = (bounds.size.width-(self.cols-1)*self.minCircleInteritemSpacing)/self.cols;
    CGFloat cellWidth = self.circleRadius*2;
    cellWidth = MAX(cellWidth,minCellWidth);
    cellWidth = MIN(cellWidth,maxCellWidth);
    
    //计算cellHeight
    CGFloat minCellHeight = (bounds.size.height-(self.rows-1)*self.circleInteritemSpacing)/self.rows;
    CGFloat maxCellHeight = (bounds.size.height-(self.rows-1)*self.minCircleInteritemSpacing)/self.rows;
    CGFloat cellHeight = self.circleRadius*2;
    cellHeight = MAX(cellHeight,minCellHeight);
    cellHeight = MIN(cellHeight,maxCellHeight);
    //
    CGFloat cellLength = MIN(cellWidth,cellHeight);//圆圆的直径值
    CGFloat spaceW = (bounds.size.width-self.cols*cellLength)/(self.cols-1);
    CGFloat spaceH = (bounds.size.height-self.rows*cellLength)/(self.rows-1);
    CGFloat space = MIN(spaceW,spaceH);//间隔
    space = MAX(space,self.minCircleInteritemSpacing);
    space = MIN(space,self.circleInteritemSpacing);
    
    CGRect innerBounds = bounds;
    innerBounds.size.width = self.cols*cellLength+(self.cols-1)*space;
    innerBounds.size.height = self.rows*cellLength+(self.rows-1)*space;
    innerBounds.origin.x = bounds.origin.x+(bounds.size.width-innerBounds.size.width)*0.5;
    innerBounds.origin.y = bounds.origin.y+(bounds.size.height-innerBounds.size.height)*0.5;
    
    CGRect f1 = innerBounds;
    f1.size = CGSizeMake(cellLength, cellLength);
    NSInteger cellIndex = 0;
    MKUITestCircleCellBase *cell;
    for(int i=0;i<self.rows;i++){
        for(int j=0;j<self.cols;j++){
            cellIndex = i*self.cols+j;
            if(cellIndex>=self.circleCells.count)continue;
            cell = self.circleCells[cellIndex];
            cell.frame = f1;
            f1.origin.x = CGRectGetMaxX(f1)+space;
        }
        f1.origin.x = innerBounds.origin.x;
        f1.origin.y = CGRectGetMaxY(f1)+space;
    }
    [self setNeedsDisplay];
    [self reloadCellsIfNeeded];
}
- (void)setContentInsets:(UIEdgeInsets)contentInsets{
    if(UIEdgeInsetsEqualToEdgeInsets(_contentInsets, contentInsets))return;
    _contentInsets = contentInsets;
    [self setNeedReloadCells];
}
- (void)setCircleInteritemSpacing:(CGFloat)circleInteritemSpacing{
    if(_circleInteritemSpacing==circleInteritemSpacing)return;
    _circleInteritemSpacing = circleInteritemSpacing;
    [self setNeedReloadCells];
}
- (void)setMinCircleInteritemSpacing:(CGFloat)minCircleInteritemSpacing{
    if(_minCircleInteritemSpacing==minCircleInteritemSpacing)return;
    _minCircleInteritemSpacing = minCircleInteritemSpacing;
    [self setNeedReloadCells];
}
- (void)setCircleRadius:(CGFloat)circleRadius{
    if(_circleRadius==circleRadius)return;
    _circleRadius = circleRadius;
    [self setNeedReloadCells];
}
- (void)setMinCircleRadius:(CGFloat)minCircleRadius{
    if(_minCircleRadius==minCircleRadius)return;
    _minCircleRadius = minCircleRadius;
    [self setNeedReloadCells];
}
- (void)setLineWidth:(CGFloat)lineWidth{
    if(_lineWidth==lineWidth)return;
    _lineWidth = lineWidth;
    [self setNeedReloadCells];
}
- (void)setLineColor:(UIColor *)lineColor{
    if(_lineColor==lineColor||[_lineColor isEqual:lineColor])return;
    _lineColor = lineColor;
    [self setNeedReloadCells];
}
- (void)setSelectedCircleIndexes:(NSArray<NSNumber *> *)selectedCircleIndexes{
    if([_selectedCircleIndexes isEqualToArray:selectedCircleIndexes])return;
    [_selectedCircleIndexes removeAllObjects];
    [_selectedCircleIndexes addObjectsFromArray:selectedCircleIndexes];
    [self.selectedCircleCells removeAllObjects];
    for(NSNumber *n in selectedCircleIndexes){
        NSInteger cellIndex = n.integerValue;
        if(cellIndex<0||cellIndex>=self.circleCells.count)continue;
        MKUITestCircleCellBase *cell = self.circleCells[cellIndex];
        [self.selectedCircleCells addObject:cell];
    }
    [self setNeedReloadCells];
}
- (NSArray<NSNumber *> *)selectedCircleIndexes{
    return [_selectedCircleIndexes copy];
}
- (void)initCells{
    for(UIView *v in self.contentView.subviews) [v removeFromSuperview];
    NSMutableArray<MKUITestCircleCellBase *> *cells = [[NSMutableArray alloc] initWithCapacity:self.cols*self.rows];
    Class cellClass = self.circleCellClass;
    if(!cellClass) cellClass = MKUITestCircleCell.class;
    for(int i=0;i<self.rows;i++){
        for(int j=0;j<self.cols;j++){
            MKUITestCircleCellBase *cell = [[cellClass alloc] init];
            cell.cellIndex = i*self.cols+j;
            [self.contentView addSubview:cell];
            [cells addObject:cell];
            [cell reloadCell];
        }
    }
    self.circleCells = cells;
    self.lineColor = [cellClass tintColorWithSelected:YES];
    [self setNeedReloadCells];
}
- (void)setCircleCellClass:(Class)circleCellClass{
    if(_circleCellClass==circleCellClass)return;
    _circleCellClass = circleCellClass;
    [self initCells];
}
- (void)setIsTrackHidden:(BOOL)isTrackHidden{
    if(_isTrackHidden==isTrackHidden)return;
    _isTrackHidden = isTrackHidden;
    [self setNeedReloadCells];
}
- (void)setNeedReloadCells{
    self.needReloadCells = YES;
    [self setNeedsLayout];
    [self setNeedsDisplay];
}
- (void)reloadCellsIfNeeded{
    if(!self.needReloadCells)return;
    self.needReloadCells = NO;
    
    [self.selectedCircleCells removeAllObjects];
    for(NSNumber *n in _selectedCircleIndexes){
        NSInteger cellIndex = n.integerValue;
        if(cellIndex<0||cellIndex>=self.circleCells.count)continue;
        MKUITestCircleCellBase *cell = self.circleCells[cellIndex];
        [self.selectedCircleCells addObject:cell];
    }
    
    NSSet<NSNumber *> *sets = [NSSet setWithArray:_selectedCircleIndexes];
    for(MKUITestCircleCellBase *cell in self.circleCells){
        cell.isTrackHidden = self.isTrackHidden;
        BOOL selected = [sets containsObject:@(cell.cellIndex)];
        cell.selected = selected;
        [cell reloadCell];
    }
    [self setNeedsLayout];
    [self setNeedsDisplay];
}
+ (NSInteger)turnsCountWithSelectedCircleIndexes:(NSArray<NSNumber *> *)selectedCircleIndexes cols:(NSInteger)cols{
    if(selectedCircleIndexes.count<3) return 0;
    NSInteger count = 0;
    for(int i=0;i<selectedCircleIndexes.count-2;i++){
        NSInteger index1 = selectedCircleIndexes[i].integerValue;
        NSInteger index2 = selectedCircleIndexes[i+1].integerValue;
        NSInteger index3 = selectedCircleIndexes[i+2].integerValue;
        
        CGPoint line1Point1 = CGPointMake(index1%cols, (NSInteger)index1/cols);
        CGPoint line1Point2 = CGPointMake(index2%cols, (NSInteger)index2/cols);
        CGPoint line2Point1 = line1Point2;
        CGPoint line2Point2 = CGPointMake(index3%cols, (NSInteger)index3/cols);
        BOOL parallel = [self areLinesParallelUsingVectors:line1Point1 line1Point2:line1Point2 line2Point1:line2Point1 line2Point2:line2Point2];//是否平行
        if(!parallel){
            count++;
        }
    }
    return count;
}
#pragma mark - draw
- (void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    if(self.isTrackHidden)return;
    //绘制连线
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [self _drawLines:ctx rect:rect];
}
- (void)_drawLines:(CGContextRef)ctx rect:(CGRect)rect{
    if(!self.lineColor)return;
    NSArray<MKUITestCircleCellBase *> *cells = self.selectedCircleCells;
    //添加路径
    CGContextAddRect(ctx, rect);
    //剪裁圆圈
    for(MKUITestCircleCellBase *cell in self.circleCells){
        CGRect f = [cell.superview convertRect:cell.frame toView:self];
        CGContextAddEllipseInRect(ctx, f);
    }
    //剪裁上下文
    CGContextEOClip(ctx);
    
    for(int i=0;i<cells.count;i++){
        MKUITestCircleCellBase *cell = cells[i];
        CGRect f = [cell.superview convertRect:cell.frame toView:self];
        if(i==0){//起点
            CGContextMoveToPoint(ctx, CGRectGetMidX(f), CGRectGetMidY(f));
        }else{//连线
            CGContextAddLineToPoint(ctx, CGRectGetMidX(f), CGRectGetMidY(f));
        }
    }
    // 连接最后一个按钮到手指当前触摸得点
    if(self.isTouching && cells.count>0){
        CGPoint touching = [self convertPoint:self.touchingPoint fromView:self.contentView];//转换到self坐标系中
        CGContextAddLineToPoint(ctx, touching.x, touching.y);
    }
    
    //线条转角样式
    CGContextSetLineCap(ctx, kCGLineCapRound);
    CGContextSetLineJoin(ctx, kCGLineJoinRound);
    
    // 设置绘图的属性
    CGContextSetLineWidth(ctx, self.lineWidth);
    
    // 线条颜色
    CGContextSetStrokeColorWithColor(ctx, (self.lineColor?:UIColor.clearColor).CGColor);
    
    //渲染路径
    CGContextStrokePath(ctx);
}

#pragma mark - touch
//- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
//    UIView *r = [super hitTest:point withEvent:event];
//    NSLog(@"hitTest:%@",r);
//    return r;
//}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"touchesBegan");
//    [super touchesBegan:touches withEvent:event];//取消事件链
    if([self.delegate respondsToSelector:@selector(circleGestureViewWillBeginTouching:)]){
        [self.delegate circleGestureViewWillBeginTouching:self];
    }
    
    self.isTouching = YES;
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.contentView];
    self.touchingPoint = point;
    BOOL needNotifyChange = NO;
    if(self.clearSelectionWhenTouchBegin){
        needNotifyChange = _selectedCircleIndexes.count>0;
        self.selectedCircleIndexes = nil;
        if(needNotifyChange) [self _notifySelectedChange];
        for(MKUITestCircleCellBase *cell in self.selectedCircleCells){
            [cell setSelected:NO animated:NO];
        }
    }
    [self _touchingToPoing:point];
}
- (void)_notifySelectedChange{
    if([self.delegate respondsToSelector:@selector(circleGestureView:didSelectedCircleIndexes:)]){
        [self.delegate circleGestureView:self didSelectedCircleIndexes:self.selectedCircleIndexes];
    }
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"touchesMoved");
//    [super touchesMoved:touches withEvent:event];
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.contentView];
    [self _touchingToPoing:point];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"touchesEnded");
//    [super touchesEnded:touches withEvent:event];
    [self _endTouching:touches withEvent:event];
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"touchesCancelled");
//    [super touchesCancelled:touches withEvent:event];
    [self _endTouching:touches withEvent:event];
}
- (void)_touchingToPoing:(CGPoint)point{
    self.touchingPoint = point;
    MKUITestCircleCellBase *touchingCell = [self cellForPoint:point];
    if(touchingCell && ![self.selectedCircleCells containsObject:touchingCell]){
        MKUITestCircleCellBase *preTouchingCell = self.selectedCircleCells.lastObject;
        if(!preTouchingCell){//第一次选中
            [self addTouchingCircleCell:touchingCell animated:YES];
        }else{//查找p1到p2之间，是否有经过其他cell
            CGPoint p1 = [preTouchingCell.superview convertPoint:CGPointMake(CGRectGetMidX(preTouchingCell.frame), CGRectGetMidY(preTouchingCell.frame)) toView:self.contentView];//转换到contentView坐标系中
            CGPoint p2 = [touchingCell.superview convertPoint:CGPointMake(CGRectGetMidX(touchingCell.frame), CGRectGetMidY(touchingCell.frame)) toView:self.contentView];//转换到contentView坐标系中
            for(MKUITestCircleCellBase *c in self.circleCells){
                if(c==preTouchingCell||c==touchingCell)continue;
                if([self.selectedCircleCells containsObject:c]) continue;
                CGPoint center = [c.superview convertPoint:CGPointMake(CGRectGetMidX(c.frame), CGRectGetMidY(c.frame)) toView:self.contentView];
                BOOL lineIntersects = [self.class segmentIntersectsCircle:p1 segmentEnd:p2 circleCenter:center radius:c.frame.size.width/2];
                if(lineIntersects){
                    [self addTouchingCircleCell:c animated:YES];
                }
            }
            [self addTouchingCircleCell:touchingCell animated:YES];
        }
    }
    [self setNeedsDisplay];
}
- (void)addTouchingCircleCell:(MKUITestCircleCellBase *)cell animated:(BOOL)animated{
    if(!cell)return;
    [cell setSelected:YES animated:animated];
    [_selectedCircleIndexes addObject:@(cell.cellIndex)];
    [self.selectedCircleCells addObject:cell];
    [self _notifySelectedChange];
}
- (void)_endTouching:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.contentView];
    self.touchingPoint = point;
    [self _touchingToPoing:point];
    self.isTouching = NO;
    [self setNeedsLayout];
    if([self.delegate respondsToSelector:@selector(circleGestureViewDidEndTouching:)]){
        [self.delegate circleGestureViewDidEndTouching:self];
    }
}
- (MKUITestCircleCellBase *)cellForPoint:(CGPoint)point{//返回指定点对应的cell,point的坐标系为self.contentView
    MKUITestCircleCellBase *cell = nil;
    for(MKUITestCircleCellBase *c in self.circleCells){
        CGPoint p = [c.superview convertPoint:point toView:c];//置换到cell的坐标系
        if([c pointInside:p withEvent:nil]){
            cell = c;
            break;
        }
    }
    return cell;
}
#pragma mark - 数学计算
// 计算两点间距离
+ (CGFloat)distanceBetweenPoints:(CGPoint)p1 p2:(CGPoint)p2{
    CGFloat dx = p2.x - p1.x;
    CGFloat dy = p2.y - p1.y;
    CGFloat r = sqrt(dx*dx + dy*dy);
    return r;
}
// 判断线段与圆是否相交
+ (BOOL)segmentIntersectsCircle:(CGPoint)segmentStart segmentEnd:(CGPoint)segmentEnd circleCenter:(CGPoint)circleCenter radius:(CGFloat)radius{
    // 1. 检查线段端点是否在圆内
    if ([self distanceBetweenPoints:segmentStart p2:circleCenter] <= radius ||
        [self distanceBetweenPoints:segmentEnd p2:circleCenter] <= radius) {
        return YES;
    }
    
    // 2. 计算圆心到线段的距离
    CGFloat segmentLength = [self distanceBetweenPoints:segmentStart p2:segmentEnd];
    if (segmentLength < 0.001) {
        // 线段长度接近0，视为点
        return [self distanceBetweenPoints:segmentStart p2:circleCenter] <= radius;
    }
    
    // 计算投影比例
    CGFloat u = ((circleCenter.x - segmentStart.x) * (segmentEnd.x - segmentStart.x) +
                (circleCenter.y - segmentStart.y) * (segmentEnd.y - segmentStart.y)) /
               (segmentLength * segmentLength);
    
    CGPoint closestPoint;
    if (u < 0.0) {
        closestPoint = segmentStart;
    } else if (u > 1.0) {
        closestPoint = segmentEnd;
    } else {
        closestPoint = CGPointMake(segmentStart.x + u * (segmentEnd.x - segmentStart.x),
                                 segmentStart.y + u * (segmentEnd.y - segmentStart.y));
    }
    
    // 检查最近点是否在圆内
    if ([self distanceBetweenPoints:closestPoint p2:circleCenter] > radius) {
        return NO;
    }
    
    // 3. 检查线段是否穿过圆
    // 计算线段方向向量
    CGFloat dx = segmentEnd.x - segmentStart.x;
    CGFloat dy = segmentEnd.y - segmentStart.y;
    
    // 线段方程参数: p = segmentStart + t*(segmentEnd-segmentStart)
    // 圆方程: (x - circleCenter.x)^2 + (y - circleCenter.y)^2 = radius^2
    
    // 代入后得到二次方程 at^2 + bt + c = 0
    CGFloat A = dx*dx + dy*dy;
    CGFloat B = 2 * (dx * (segmentStart.x - circleCenter.x) + dy * (segmentStart.y - circleCenter.y));
    CGFloat C = pow(segmentStart.x - circleCenter.x, 2) + pow(segmentStart.y - circleCenter.y, 2) - radius*radius;
    
    CGFloat discriminant = B*B - 4*A*C;
    
    if (discriminant < 0) {
        return NO; // 无实数解
    }
    
    discriminant = sqrt(discriminant);
    CGFloat t1 = (-B + discriminant) / (2*A);
    CGFloat t2 = (-B - discriminant) / (2*A);
    
    // 检查解是否在线段范围内(0 <= t <= 1)
    return (t1 >= 0 && t1 <= 1) || (t2 >= 0 && t2 <= 1);
}
//判断两条直线是否平行的方法(使用向量叉积)
+ (BOOL)areLinesParallelUsingVectors:(CGPoint)line1Point1 line1Point2:(CGPoint)line1Point2 line2Point1:(CGPoint)line2Point1 line2Point2:(CGPoint)line2Point2{
    // 计算第一条直线的方向向量
    CGPoint vec1 = CGPointMake(line1Point2.x - line1Point1.x,
                              line1Point2.y - line1Point1.y);
    
    // 计算第二条直线的方向向量
    CGPoint vec2 = CGPointMake(line2Point2.x - line2Point1.x,
                              line2Point2.y - line2Point1.y);
    
    // 计算叉积（2D向量的叉积是一个标量）
    CGFloat crossProduct = vec1.x * vec2.y - vec1.y * vec2.x;
    
    // 如果叉积接近0，则向量平行
    return fabs(crossProduct) < 0.0001;
}
@end
